package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
        List<CourseCategoryTreeDto> treeNodes = courseCategoryMapper.selectTreeNodes(id);
        List<CourseCategoryTreeDto> result = new ArrayList<>();

        //封装成前端的格式
        //list转为map
        Map<String, CourseCategoryTreeDto> map = treeNodes.stream()
                .collect(Collectors.toMap(
                        CourseCategoryTreeDto::getId,
                        CourseCategoryTreeDto -> CourseCategoryTreeDto
                ));

        for (CourseCategoryTreeDto treeNode : treeNodes) {
            if(treeNode.getParentid().equals("0")){
                continue;
            }else if(treeNode.getParentid().equals("1")){ //一级分类直接添加到list
                result.add(treeNode);
            }else{ //二级分类要添加到一级分类的子类中
                CourseCategoryTreeDto treeDto = map.get(treeNode.getParentid());
                if(treeDto.getChildrenTreeNodes() == null){
                    List<CourseCategoryTreeDto> list = new ArrayList<>();
                    list.add(treeNode);
                    treeDto.setChildrenTreeNodes(list);
                }else{
                    List<CourseCategoryTreeDto> childrenTreeNodes = treeDto.getChildrenTreeNodes();
                    childrenTreeNodes.add(treeNode);
                    treeDto.setChildrenTreeNodes(childrenTreeNodes);
                }
            }
        }
        return result;
    }
}
